package com.javase.datatype;

/**
 * @author wsh
 * @date 2021-09-15 09:29
 */
public class BinaryUtil {
    public static void main(String[] args) {
        System.out.println("---- 显示二进制数（0B开头表示二进制）");
        System.out.println(0B10000000);
        System.out.println(0B11111111);

        System.out.println("---- byte：");
        System.out.println(showBinaryString((byte) 1));
        System.out.println(showBinaryString((byte) -1));

        System.out.println("---- int：");
        System.out.println(showBinaryString(1));
        System.out.println(showBinaryString(-1));
        System.out.println(0xFF);
        System.out.println(0x100);
    }

    /**
     * 以字符串形式显示二进制值
     */
    public static String showBinaryString(byte n) {
        return Integer.toBinaryString((n & 0xFF) + 0x100).substring(1);
    }

    public static String showBinaryString(int n) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Integer.SIZE; i++) {
            int t = (n & Integer.MIN_VALUE >>> i) >>> (Integer.SIZE - 1 - i);
            sb.append(t);
        }
        return sb.toString();
    }

    /**
     * 取原码
     */
    public static String getInverseCodeBy(byte n) {
        if (n >= 0) {
            // 正数的补码：与原码相同
            return showBinaryString(n);
        } else {
            // TODO 负数的补码：原码的反码再加1
            return "";
        }
    }

    /**
     * 取反码
     */
    public static String getInverseCodeBy(String n) {
        // TODO
        return "";
    }

    /**
     * 取补码
     */
    public static String getComplementOfByte(byte n) {
        // TODO
        return "";
    }
}
